package com.mediacloud.app.newsmodule.fragment

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import androidx.core.view.ViewCompat
import com.donkingliang.consecutivescroller.ConsecutiveScrollerLayout
import com.donkingliang.consecutivescroller.IConsecutiveScroller
import com.donkingliang.consecutivescroller.LayoutParamsUtils

class ConsecutiveScrollerLayoutX(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : ConsecutiveScrollerLayout(context, attrs, defStyleAttr) {
    constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context?) : this(context, null)

    fun addViewInLayoutX(child: View, index: Int) {


        addViewInLayout(child, index, LayoutParams(1, -2))
        if (isConsecutiveScrollerChild(child)) {
            val scrollChild = getScrollChild(child)
            scrollChild?.let {
                it.isVerticalScrollBarEnabled = false
                it.isHorizontalScrollBarEnabled = false
                it.overScrollMode = OVER_SCROLL_NEVER
                ViewCompat.setNestedScrollingEnabled(it, false)
            }
            if (scrollChild is IConsecutiveScroller) {
                val views = (scrollChild as IConsecutiveScroller).scrolledViews
                if (views != null && !views.isEmpty()) {
                    val size = views.size
                    for (i in 0 until size) {
                        views[i]?.let {
                            it.isVerticalScrollBarEnabled = false
                            it.isHorizontalScrollBarEnabled = false
                            it.overScrollMode = OVER_SCROLL_NEVER
                            ViewCompat.setNestedScrollingEnabled(it, false)
                        }
                    }
                }
            }
        }

        if (child is ViewGroup) {
            child.clipToPadding = false
        }

    }


    fun isConsecutiveScrollerChild(view: View?): Boolean {
        if (view != null) {
            val lp = view.layoutParams
            return if (lp is LayoutParams) {
                lp.isConsecutive
            } else true
        }
        return false
    }

    fun getScrollChild(view: View?): View? {
        if (view != null) {
            val lp = view.layoutParams
            if (lp is LayoutParams) {
                val childId = lp.scrollChild
                val child = view.findViewById<View>(childId)
                if (child != null) {
                    return child
                }
            }
        }
        return view
    }
}